package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 *
 * @author cxb
 * @date 2025-09-30
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private ElderMapper elderMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住详情
     *
     * @param id
     * @return
     */
    @Override
    @Transactional
    public CheckInDetailVo detail(Long id) {
        //checkInElderVo信息填入
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        CheckIn checkIn = checkInMapper.selectById(id);
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        BeanUtils.copyProperties(elder, checkInElderVo);
        //ElderFamilyVo信息填入
        List<ElderFamilyVo> elderFamilyVoList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(checkIn.getRemark())) {
            elderFamilyVoList.addAll(JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class));
        }
        //checkInConfigVo信息填入
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        LambdaQueryWrapper<CheckInConfig> checkInConfigLambdaQueryWrapper = new LambdaQueryWrapper<>();
        checkInConfigLambdaQueryWrapper.eq(CheckInConfig::getCheckInId, checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(checkInConfigLambdaQueryWrapper);
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        //contract信息填入
        LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
        contractLambdaQueryWrapper.eq(Contract::getElderId, elder.getId());
        Contract contract = contractMapper.selectOne(contractLambdaQueryWrapper);
        //将所有信息填充到checkInDetailVo
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);


        return checkInDetailVo;
    }

    /**
     * 入住申请
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 判断老人是否已入住
        isCheckIn(checkInApplyDto);
        //更新床位状态为已入住
        Bed bed = changeBedStatus(checkInApplyDto);
        //新增或更新老人信息
        Elder elder = insertOrUpdateElder(checkInApplyDto, bed);
        //新增签约办理
        saveContract(checkInApplyDto, elder);
        //新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto, elder, bed);
        //新增入住配置
        saveCheckInConfig(checkInApplyDto, checkIn);
    }

    /**
     * 新增入住配置
     *
     * @param checkInApplyDto
     * @param checkIn
     */

    private void saveCheckInConfig(CheckInApplyDto checkInApplyDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insertCheckInConfig(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param checkInApplyDto
     * @param elder
     * @param bed
     * @return
     */
    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setStatus(0);
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insertCheckIn(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     *
     * @param checkInApplyDto
     * @param elder
     */
    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        if (LocalDateTime.now().isBefore(contract.getStartDate())) {
            contract.setStatus(0);
        } else if (LocalDateTime.now().isAfter(contract.getEndDate())) {
            contract.setStatus(2);
        } else {
            contract.setStatus(1);
        }
        contractMapper.insertContract(contract);
    }

    /**
     * 新增或更新老人信息
     *
     * @param checkInApplyDto
     * @param bed
     * @return
     */
    private Elder insertOrUpdateElder(CheckInApplyDto checkInApplyDto, Bed bed) {
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        elder.setStatus(1);
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()).ne(Elder::getStatus, 1);
        Elder elderQuery = elderMapper.selectOne(elderLambdaQueryWrapper);
        if (ObjectUtil.isNotEmpty(elderQuery)) {
            elder.setId(elderQuery.getId());
            elderMapper.updateElder(elder);
        } else {
            elderMapper.insertElder(elder);
        }
        return elder;
    }

    /**
     * 更新床位状态为已入住
     *
     * @param checkInApplyDto
     * @return
     */
    private Bed changeBedStatus(CheckInApplyDto checkInApplyDto) {
        Bed bed = bedMapper.selectBedById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        return bed;
    }

    /**
     * 判断老人是否已入住
     *
     * @param checkInApplyDto
     */
    private void isCheckIn(CheckInApplyDto checkInApplyDto) {
        LambdaQueryWrapper<Elder> elderLambdaQueryWrapper = new LambdaQueryWrapper<>();
        elderLambdaQueryWrapper.eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()).eq(Elder::getStatus, 1);
        Elder elder = elderMapper.selectOne(elderLambdaQueryWrapper);
        if (ObjectUtil.isNotEmpty(elder)) {
            throw new BaseException("已办理入住，请重新确认");
        }
    }
}
